import { render } from "solid-js/web";
import { For, Show, onMount, createSignal, createEffect } from "solid-js";
import { fetchAskData } from "./util/tools";
import SrtContainer from "./Srt";

import "./App.css"

function App() {
  const get = 0, set = 1;
  const seasons = createSignal<string[]>([]);
  const selectedSeason = createSignal("");
  const selectedRepeat = createSignal(5);
  const title = createSignal("");
  const repeatList = ["2", "3", "4", "5", "6", "7", "8", "9"];
  let elSeasons: HTMLSelectElement;
  let elRepeats: HTMLSelectElement;
  let elVideo: HTMLVideoElement;
  onMount(async () => {
    elRepeats.options.selectedIndex = selectedRepeat[get]() - 2;
    const { list, title: pageTitle }: { list: string[]; title: string; } = await fetchAskData("getSeasons", { level: 1 }, true);
    title[set](pageTitle);
    document.getElementsByTagName("title")[0].innerText = pageTitle;
    seasons[set](list);
    const item = list[0];
    setTimeout(() => selectedSeason[set](item), 100);
  })

  function seasonChange(e: Event) {
    selectedSeason[set]("");
    const options = elSeasons.options;
    const item = options[options.selectedIndex].value;
    setTimeout(() => selectedSeason[set](item), 100);
  }
  function repeatChange(e: Event) {
    const options = elRepeats.options;
    const item = options[options.selectedIndex].value;
    selectedRepeat[set](parseInt(item));
  }

  return (
    <div>
      <div class="player">
        <div class="movie-name">
          <span>{title[get]()}</span>
          <span class="season-list">
            <select ref={elSeasons!} onChange={seasonChange}>
              <For each={seasons[get]()}>
                {item => <option>{item}</option>}
              </For>
            </select>
          </span>
          <span class="episode-list" />
          <span class="repeat-list">
            <select ref={elRepeats!} onChange={repeatChange}>
              <For each={repeatList}>
                {item => <option>{item}</option>}
              </For>
            </select>
          </span>
        </div>
        <video ref={elVideo!} controls />
      </div>
      <div class="srt-container">
        <Show when={selectedSeason[get]()}>
          <SrtContainer season={selectedSeason[get]()} elVideo={elVideo!} selectedRepeat={selectedRepeat} />
        </Show>
      </div>
    </div>
  );
}

render(() => <App />, document.getElementById("root")!);
